#!/usr/bin/env python
import os
import argparse
import shutil
from setup_tools import project_dir, EncryptProject

def cmd():
    parser = argparse.ArgumentParser('new package...')
    subparsers = parser.add_subparsers(dest='command', help='new|enc')

    new_parser = subparsers.add_parser('new', help='new a package')

    new_parser.add_argument('-p', '--package_dir', default='./', help='input project dir')

    enc_parser = subparsers.add_parser('enc', help='encrypt a package')
    
    enc_parser.add_argument('-p', '--package_dir', default='./', help='input project dir')
    enc_parser.add_argument('-e', '--exclude', nargs='+', default=['test'], help='exclude dir')

    return parser

def new_pack(opt):
    opt.package_dir = os.path.abspath(opt.package_dir)
    if os.path.exists(opt.package_dir):
        raise RuntimeError('%s is already exists' % opt.package_dir)

    shutil.copytree(project_dir, opt.package_dir)

    script_keep = os.path.join(project_dir, 'scripts', '.keep')
    cache_keep = os.path.join(project_dir, '__pycache__')

    if os.path.exists(script_keep):
        os.remove(script_keep)
    if os.path.exists(cache_keep):
        shutil.rmtree(cache_keep)

    project_name = os.path.basename(opt.package_dir)
    src_source_dir = os.path.join(opt.package_dir, 'src', 'project') 
    dst_source_dir = os.path.join(opt.package_dir, 'src', project_name)
    shutil.move(src_source_dir, dst_source_dir)

    print('project create in %s' % opt.package_dir)

def enc_pack(opt):
    ep = EncryptProject(opt.package_dir, exclude=opt.exclude)

    ep.setup()

if __name__ == '__main__':
    parser = cmd()
    opt = parser.parse_args()

    if opt.command == 'new':
        new_pack(opt)
    elif opt.command == 'enc':
        enc_pack(opt) 
    else:
        pass